<template>
  <el-dialog v-el-drag-dialog :title="!form.brandId?'新建支付渠道':'编辑支付渠道'" :visible.sync="visible" :append-to-body="appendToBody" :before-close="onClose">
    <el-form ref="channelForm" :model="form" :rules="rules" label-width="120px" :disabled="!hasLoaded">
      <el-form-item hidden>
        <el-input v-model="form.id" hidden />
      </el-form-item>

      <el-card>
        <el-col :span="12">
          <el-form-item label="appId" prop="appId">
            <el-input v-model="form.appId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="商户号" prop="mchId">
            <el-input v-model="form.mchId" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支付平台" prop="channelId">
            <el-select v-model="form.channelId">
              <el-option
                v-for="item in optionOfChannel"
                :key="item.dictCode"
                :label="item.dictLabel"
                :value="item.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户端类型" prop="channelCode">
            <el-input v-model="form.channelCode" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="应用图标地址" prop="icon">
            <el-input v-model="form.icon" />
          </el-form-item>
        </el-col>
        <el-col :span="24" style="display: flex;margin-bottom: 22px;">
          <label class="el-form-item__label" style="width: 120px">根证书</label>
          <el-upload
            class="upload-demo d-flex"
            :headers="headers"
            :action="uploadUrl"
            :data="extraData"
            :before-remove="beforeRootCertRemove"
            :limit="1"
            with-credentials
            :on-exceed="handleExceed"
            :on-success="handleRootCertSuccess"
            :file-list="rootCertList"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-col>
        <el-col :span="24" style="display: flex;margin-bottom: 22px;">
          <label class="el-form-item__label" style="width: 120px">私钥证书</label>
          <el-upload
            class="upload-demo d-flex"
            :headers="headers"
            :action="uploadUrl"
            :data="extraData"
            :before-remove="beforePrivateCertRemove"
            :limit="1"
            with-credentials
            :on-exceed="handleExceed"
            :on-success="handlePrivateCertSuccess"
            :file-list="privateCertList"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-col>
        <el-col :span="24" style="display: flex;margin-bottom: 22px;">
          <label class="el-form-item__label" style="width: 120px">公钥证书</label>
          <el-upload
            class="upload-demo d-flex"
            :headers="headers"
            :action="uploadUrl"
            :data="extraData"
            :before-remove="beforePublicCertRemove"
            :limit="1"
            with-credentials
            :on-exceed="handleExceed"
            :on-success="handlePublicCertSuccess"
            :file-list="publicCertList"
          >
            <el-button type="primary">上传</el-button>
          </el-upload>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付回调地址" prop="payNotifyUrl">
            <el-input v-model="form.payNotifyUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="退款回调地址" prop="refundNotifyUrl">
            <el-input v-model="form.refundNotifyUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="完成回调地址" prop="payReturnUrl">
            <el-input v-model="form.payReturnUrl" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="额外参数" prop="param">
            <el-input
              type="textarea"
              v-model="form.param"
              resize="vertical"
              :autosize="{ minRows: 2, maxRows: 10 }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              v-model="form.remark"
              resize="vertical"
              :autosize="{ minRows: 2, maxRows: 4 }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="状态" prop="status">
            <el-radio-group v-model="form.status">
              <el-radio-button v-for="item in optionOfAvailable" :key="'option_' + item.dictValue" :label="item.dictValue">
                {{ item.dictLabel }}
              </el-radio-button>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-card>
    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button v-if="hasLoaded" type="primary" icon="el-icon-check" @click="onSubmit">确 定</el-button>
      <el-button icon="el-icon-close" @click="onClose">关 闭</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { paymentChannelLoad, paymentChannelSave } from '@/api/mall/payment/channel'
import { loadFile, deleteFile } from '@/api/tool/file'
import { getAuthenticationHeader } from '@/utils/store'

export default {
  name: 'PaymentChannelFormDialog',
  data() {
    return {
      visible: false,
      appendToBody: false,
      hasLoaded: false,
      form: {
        id: undefined,
        appId: undefined,
        channelId: undefined,
        channelCode: undefined,
        mchId: undefined,
        icon: undefined,
        privateCert: undefined,
        publicCert: undefined,
        rootCert: undefined,
        payNotifyUrl: undefined,
        payReturnUrl: undefined,
        refundNotifyUrl: undefined,
        param: undefined,
        remark: undefined,
        status: '0'
      },
      rules: {
        appId: [{ required: true, message: 'appId不能为空' }],
        channelId: [{ required: true, message: '支付平台不能为空' }],
        channelCode: [{ required: true, message: '客户端类型不能为空' }],
        mchId: [{ required: true, message: '商户号不能为空' }],
        privateCert: [{ required: true, message: '私钥证书不能为空' }],
        publicCert: [{ required: true, message: '公钥证书不能为空' }]
      },
      optionOfChannel: [],
      optionOfAvailable: [],
      headers: getAuthenticationHeader(),
      uploadUrl: this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/upload`,
      extraData: {
        path: 'cert'
      },
      rootCertList: [],
      privateCertList: [],
      publicCertList: []
    }
  },
  methods: {
    init(id) {
      this.hasLoaded = false
      this.form.id = id || null
      this.visible = true
      this.$nextTick(() => {
        this.getDictData()
        this.loadForm(id)
      })
    },
    loadForm(id) {
      paymentChannelLoad({ 'id': id }).then(response => {
        this.form = this.$api.objectUpdate(this.form, response.param)
        if (this.form.rootCert) {
          loadFile({ 'fileId': this.form.rootCert }).then(response => {
            if (response.param) {
              this.rootCertList.push({
                name: response.param.originalFilename,
                url: this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download/${response.param.fileId}`
              })
            }
          })
        }
        if (this.form.privateCert) {
          loadFile({ 'fileId': this.form.privateCert }).then(response => {
            if (response.param) {
              this.privateCertList.push({
                name: response.param.originalFilename,
                url: this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download/${response.param.fileId}`
              })
            }
          })
        }
        if (this.form.publicCert) {
          loadFile({ 'fileId': this.form.publicCert }).then(response => {
            if (response.param) {
              this.publicCertList.push({
                name: response.param.originalFilename,
                url: this.$store.state.app.server_api + `${process.env.VUE_APP_MODULE_ADMIN_API}/api/file/download/${response.param.fileId}`
              })
            }
          })
        }
        // 判断当前用户权限
        this.hasLoaded = this.$perm.hasPermissionOr(['pay:channel:edit'])
      }).catch(() => {})
    },
    getDictData() {
      const that = this
      this.$http.all([this.$dictGroup('sys_pay_type'), this.$dictGroup('sys_available_type')])
        .then(this.$http.spread(function(response1, response2) {
          that.optionOfChannel = response1
          that.optionOfAvailable = response2
        }))
    },
    handleExceed(files, fileList) {
      this.$modal.msgWarning(`只能选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    handleRootCertSuccess(response, file, fileList) {
      this.form.rootCert = response.param
      const fileId = response.param
      fileList.map((file_, index) => {
        if (file.name === file_.name) {
          file_.id = fileId
        }
        return file_
      })
    },
    beforeRootCertRemove(file, fileList) {
      this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.rootCert = undefined
        deleteFile({ key: file.id })
      }).catch(e => {})
    },
    handlePrivateCertSuccess(response, file, fileList) {
      this.form.privateCert = response.param
      const fileId = response.param
      fileList.map((file_, index) => {
        if (file.name === file_.name) {
          file_.id = fileId
        }
        return file_
      })
    },
    beforePrivateCertRemove(file, fileList) {
      this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.privateCert = undefined
        deleteFile({key: file.id})
      })
    },
    handlePublicCertSuccess(response, file, fileList) {
      this.form.publicCert = response.param
      const fileId = response.param
      fileList.map((file_, index) => {
        if (file.name === file_.name) {
          file_.id = fileId
        }
        return file_
      })
    },
    beforePublicCertRemove(file, fileList) {
      this.$confirm(`确定移除 ${file.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.form.publicCert = undefined
        deleteFile({key: file.id})
      })
    },
    onSubmit() {
      this.$refs.channelForm.validate(valid => {
        if (valid) {
          paymentChannelSave(this.form).then(response => {
            this.$modal.msgSuccess(response.msg)
            this.$emit('confirmForm')
            this.onClose()
          }).catch(() => {})
        }
      })
    },
    onClose() {
      this.$refs.channelForm.resetFields()
      this.form.privateCert = undefined
      this.form.publicCert = undefined
      this.form.rootCert = undefined
      this.rootCertList = []
      this.privateCertList = []
      this.publicCertList = []
      this.visible = false
    }
  }
}
</script>
